const { merge } = require("webpack-merge");
const { baseConfig } = require("../webpack.base.config");
const path = require("path");
const webpack = require("webpack");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = merge(baseConfig, {
  mode: "production",
  output: {
    path: path.resolve(__dirname, "..", "..", "dist/client"),
    publicPath: "/public/",
  },
  optimization: {
    // 配置 optimization.moduleIds，让公共包 splitChunks 的 hash 不因为新的依赖而改变，减少非必要的 hash 变动
    moduleIds: "deterministic",
    runtimeChunk: {
      name: "runtimeChunk",
    },
    splitChunks: {
      chunks: "all", // 可以选择对哪些chunk进行优化（all|async|initial）
      minSize: 30000, // 要生成的chunk的最小大小(b)
      maxSize: 1024 * 1024 * 2, // 把提取出来的模块打包生成的文件大小不能超过maxSize值，如果超过了，要对其进行分割并打包生成新的文件。单位为字节，默认为0，表示不限制大小。
      minChunks: 1, // 分割前必须共享模块的最小引用次数
      maxAsyncRequests: 6, // 按需加载 最大并行请求量
      maxInitialRequests: 4, // 初始化页面 最大并行请求量
      automaticNameDelimiter: "_", // chunk一般名称格式为（例如vendors_main.js）该项指分隔符
      cacheGroups: {
        // 缓存组可以继承和覆盖splitChunks.*全部属性
        "console-vendors": {
          chunks: "initial",
          priority: -10, // 优先级
          reuseExistingChunk: true,
        },
        common: {
          name: `console-common`,
          priority: -20,
          chunks: "initial",
          reuseExistingChunk: true,
        },

        default: false, // 将禁用默认缓存组
      },
    },
  },
  module: {
    rules: [
      {
        test: /\.(css|less)$/i,
        use: [
          MiniCssExtractPlugin.loader,
          {
            loader: "css-loader",
            options: {
              importLoaders: 1,
              modules: {
                auto: (resourcePath) => resourcePath.endsWith(".module.less"), // 匹配.module.less文件来进行css模块化。
                localIdentName: "[local]_[hash:base64:10]",
              },
            },
          },
          {
            loader: "less-loader",
            options: {
              lessOptions: {
                modifyVars: {
                  "@primary-color": "#405ce2",
                },
                javascriptEnabled: true,
              },
            },
          },
        ],
      },
    ],
  },
  plugins: [
    new webpack.DefinePlugin({
      // 定义环境变量
      "process.env.NODE_ENV": JSON.stringify("production"),
    }),
    new MiniCssExtractPlugin({
      filename: "css/[name]_[chunkhash:8].css",
    }),
  ],
});
